<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\UnauthorizedException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    public function report(Throwable $e)
    {
        return parent::report($e); // TODO: Change the autogenerated stub
    }

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof UnauthorizedException) {
            return $this->response($exception->getMessage(), 401);
        } elseif ($exception instanceof ValidationException) {
            // Get the first message of this exception
            $message = '';
            $errors = $exception->errors();
            if (is_array($errors)) {
                $firstGroupErrors = reset($errors);
                if (is_array($firstGroupErrors)) {
                    $message = resourcebundle_get_error_message($firstGroupErrors);
                }
            }

            if (is_object($errors)) {
                $errorMessages = $errors->messages() ?? [];
                if ($errorMessages) {
                    $errorMessages = reset($errorMessages);
                    $message = implode(',', $errorMessages);
                }
            }

            return $this->response($message, 422);
        } elseif ($exception instanceof ModelNotFoundException) {
            return $this->response($exception->getMessage(), 404);
        } elseif ($exception instanceof AccessDeniedHttpException) {
            return $this->response($exception->getMessage(), 403);
        } elseif ($exception instanceof MethodNotAllowedHttpException) {
            return $this->response('Method Not Allowed', 405);
        } elseif ($exception instanceof NotFoundHttpException) {
            return $this->response('Not Found', 405);
        } elseif ($exception->getCode() == 426) {
            return $this->response($exception->getMessage(), 426);
        }

        if ($exception instanceof \Exception) {
            return $this->response($exception->getMessage(), 422);
        }
        if (!$request->wantsJson() && config('app.debug')) {
            return parent::render($request, $exception);
        }
        return parent::render($request, $exception); // TODO: Change the autogenerated stub
    }

    private function response($message, $code = 200)
    {
        $data = [
            'message' => $message
        ];
        return response()->json($data, $code);
    }
}
